package org.catdroid.englishformusicians;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

class AdapterPlayScreen extends ArrayAdapter implements OnInitListener {
	Activity a = null;
	List<Sentence> sentences = null;

	private TextToSpeech tts;

	public AdapterPlayScreen(Activity a, List<Sentence> sentences) {
		super(a, R.layout.row_play, sentences);
		this.a = a;
		this.sentences = sentences;
		tts = new TextToSpeech(a, this);
	}

	public View getView(int pos, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) {
			LayoutInflater mInflater = LayoutInflater.from(a);
			convertView = mInflater.inflate(R.layout.row_play, null);
			// Creates a ViewHolder and store references to the two children views we want to bind data to.
			holder = new ViewHolder();
			holder.linia1 = (TextView) convertView.findViewById(R.id.linia1);
			holder.linia2 = (TextView) convertView.findViewById(R.id.linia2);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final Sentence sentence = sentences.get(pos);

		holder.linia1.setText(sentence.textoVO);
		holder.linia2.setText(sentence.textoTraducido);

		convertView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				tts.speak(sentence.textoVO, TextToSpeech.QUEUE_FLUSH, null);
			}
		});
		return convertView;
	}

	private class ViewHolder {
		TextView linia1;
		TextView linia2;
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.ENGLISH);

			if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "This Language is not supported");
			}

		} else {
			Log.e("TTS", "Initilization Failed!");
		}
	}
}